package com.atguigu.PracticalProject.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.PracticalProject.app.BaseAppV1;
import com.atguigu.PracticalProject.bean.ReviewCountBean;
import com.atguigu.PracticalProject.common.Constant;
import com.atguigu.PracticalProject.util.AtguiguUtil;
import com.atguigu.PracticalProject.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsCourseReviewCountWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsCourseReviewCountWindow().init(
                4002,
                1,
                "DwsCourseReviewCountWindow",
                Constant.TOPIC_DWD_COURSE_REVIEW_INFO);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {

        //先转成pojo类
        SingleOutputStreamOperator<ReviewCountBean> reviewBeanStream = ReviewToPojo(stream);
        //判断
        SingleOutputStreamOperator<ReviewCountBean> uniqueStream = UniqueReview(reviewBeanStream);


        //开窗聚合
        SingleOutputStreamOperator<ReviewCountBean> reviewStream = WindowAndAgg(uniqueStream);

        //写入doris中
        writeToDoris(reviewStream);


    }

    private void writeToDoris(SingleOutputStreamOperator<ReviewCountBean> reviewStream) {

        reviewStream.map(
                bean -> {
                    SerializeConfig conf = new SerializeConfig();
                    conf.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    String json = JSON.toJSONString(bean, conf);
                    return JSON.toJSONString(bean, conf);
                })
                .addSink(FlinkSinkUtil.getDorisSink("DwsCourseReviewCountWindow"));
    }

    private SingleOutputStreamOperator<ReviewCountBean> WindowAndAgg(SingleOutputStreamOperator<ReviewCountBean> uniqueStream) {
        return
                uniqueStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<ReviewCountBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(
                                (bean,ts)->bean.getTs() *1000
                        )
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(
                        new ReduceFunction<ReviewCountBean>() {
                            @Override
                            public ReviewCountBean reduce(ReviewCountBean bean1,
                                                          ReviewCountBean bean2) throws Exception {
                                bean1.setUniqueUserCount(bean1.getUniqueUserCount() + bean2.getUniqueUserCount());
                                bean1.setHighReviewCount(bean1.getHighReviewCount() + bean2.getHighReviewCount());
                                bean1.setGradeCount(bean1.getGradeCount() + bean2.getGradeCount());
                                bean1.setReviewCount(bean1.getReviewCount() + bean1.getReviewCount());
                                return bean1;

                            }
                        },
                        new ProcessAllWindowFunction<ReviewCountBean, ReviewCountBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<ReviewCountBean> elements,
                                                Collector<ReviewCountBean> out) throws Exception {
                                ReviewCountBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                                bean.setCurDate(AtguiguUtil.toDate(ctx.window().getStart()));
                                out.collect(bean);

                            }
                        }
                );

    }

    private SingleOutputStreamOperator<ReviewCountBean> UniqueReview(SingleOutputStreamOperator<ReviewCountBean> reviewBeanStream) {

        return
                reviewBeanStream
                .keyBy(ReviewCountBean::getUserId)
                .process(new KeyedProcessFunction<String, ReviewCountBean, ReviewCountBean>() {
                    private ValueState<String> uniqueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        uniqueState=getRuntimeContext().getState(new ValueStateDescriptor<String>("uniqueState",String.class));
                    }

                    @Override
                    public void processElement(ReviewCountBean bean,
                                               Context ctx,
                                               Collector<ReviewCountBean> out) throws Exception {
                        if (uniqueState.value() == null){
                            bean.setUniqueUserCount(1L);
                            uniqueState.update("true");
                        }
                        out.collect(bean);

                    }
                });
    }

    private SingleOutputStreamOperator<ReviewCountBean> ReviewToPojo(DataStreamSource<String> stream) {
        return
                stream
                .map(json->{
                    JSONObject obj = JSON.parseObject(json);

                    //user_id用来判断独立用户数
                    String user_id = obj.getString("user_id");
                    long review_stars = Long.parseLong(obj.getString("review_stars"));
                    long ts = Long.parseLong(obj.getString("ts"));

                    //判断是否是好评
                    long HighReviewCount=0L;
                    if (obj.getString("review_stars") == "5"){
                        HighReviewCount=1L;
                    }
                    return new ReviewCountBean(
                            "",
                            "",
                            "",
                            "",
                            0L,
                            1L,
                            HighReviewCount,

                            review_stars,

                            ts
                    );

                });


    }
}
